//
//  OnboardingView.swift
//  Kosspot
//
//  Created by 胡辉 on 2025/7/3.
//

import SwiftUI
import SwiftUIPager
import ToastUI

struct OnboardingView: View {
    @StateObject var viewModel = OnboardingVM()
    @State private var currentPage = 0
    @StateObject var page: Page = .first()
    @Binding var showOnboarding: Bool
    @State private var showToast = false
    
    var body: some View {
        GeometryReader { geometry in
            VStack(spacing: 0) {
                HStack {
                    Button(action: {
                        showOnboarding = false
                    }) {
                        Text("跳过")
                            .font(.system(size: 14, weight: .regular))
                            .foregroundColor(Color(hex: "#B2B2B2"))
                            .frame(width: 60, height: 30)
                            .background(
                                RoundedRectangle(cornerRadius: 15)
                                    .stroke(Color(hex: "#B2B2B2"), lineWidth: 0.5)
                            )
                            .padding(.leading, 20)
                            .padding(.top, 18)
                            
                    }
                    Spacer()
                    
                    Button(action: {
                        showOnboarding = false
                    }) {
                        Image("close")
                            .font(.system(size: 16))
                            .padding(.trailing, 20)
                            .padding(.top, 20)
                    }
                    
                }
                ProgressBar(segments: 5, currentPage: $currentPage)
                    .padding(.horizontal, 20)
                    .padding(.top, 32)
                
                Pager(page: page, data: 0..<5, id: \.self, content: { index in
                    switch index {
                    case 0:
                        GenderSelectionView(selectedGender: $viewModel.gender)
                            .tag(0)
                            .ignoresSafeArea()
                    case 1:
                        BirthdaySetupView(selectedDate: $viewModel.birthday)
                            .tag(1)
                            .ignoresSafeArea()
                    case 2:
                        WeightSetupView(weight: $viewModel.weight, selectedWeightUnit: $viewModel.weightUnit)
                            .tag(2)
                            .ignoresSafeArea()
                    case 3:
                        HeightSetupView(height: $viewModel.height, selectedHeightUnit: $viewModel.heightUnit)
                            .tag(3)
                            .ignoresSafeArea()
                    case 4:
                        StepsSetupView(steps: $viewModel.steps)
                            .tag(4)
                            .ignoresSafeArea()
                    default:
                        Color(.clear)
                    }
                })
                .onPageChanged({ newPage in
                    currentPage = newPage
                })
                .frame(height: 314)
                .padding(.horizontal, 0)
                .padding(.top, 32)
                
                Button(action: {
                    if currentPage < 4 {
                        currentPage += 1
                        page.update(.next)
                    } else {
                        viewModel.updateUserInfo { result in
                            switch result {
                            case .success:
                                viewModel.error = "更新成功"
                                showToast = true
                                showOnboarding = false
                                
                            case .failure(_):
                                showToast = true
                                showOnboarding = false
                            }
                        }
                    }
                }) {
                    Image("next_step")
                        .resizable()
                        .scaledToFit()
                        .frame(width: 66, height: 66)
                }
                Spacer()
            }
            .frame(height: 544)
            .edgesIgnoringSafeArea(.top)
            .background(Color(hex: "#1E1E1E"))
            .toast(isPresented: $showToast) {
               ShowMessageView(message: viewModel.error)
               /* ToastView(viewModel.error ?? "")
                    .foregroundColor(.white)
                    .background(Color.black.opacity(0.8))
                    .cornerRadius(8)
                    .edgesIgnoringSafeArea(.all) */
            }
        }
    }
}

//#Preview {
//    OnboardingView()
//}






struct GenderSelectionView: View {
    
    @Binding private var selectedGender: Gender
    
    init(selectedGender: Binding<Gender>) {
        self._selectedGender = selectedGender
    }
    
    var body: some View {
        GeometryReader { geometry in
            VStack(alignment: .leading, spacing: 0) {
                HStack(spacing: 10) {
                    Text("请选择您的性别")
                        .font(.title2)
                        .fontWeight(.bold)
                        .foregroundColor(.white)
                        .frame(height: 24)
                    Image("gender_select")
                        .resizable()
                        .scaledToFit()
                        .frame(width: 24, height: 24)
                    Spacer()
                }
                .padding(.horizontal, 20)
                Text("针对男/女及不同年龄段的有所差异，完善个人信息，更科学地获取运动分析数据")
                    .font(.system(size: 14, weight: .regular))
                    .foregroundColor(Color(hex: "#B2B2B2"))
                    .foregroundColor(.white)
                    .padding(.horizontal, 20)
                    .padding(.top, 16)
                
//                let imageSize = min(geometry.size.width * 0.4, 140)
                let spacing = (geometry.size.width - (140 * CGFloat(Gender.allCases.count))) / CGFloat(Gender.allCases.count + 1)
                HStack(spacing: spacing) {
                    ForEach(Gender.allCases, id: \.self) { gender in
                        VStack(spacing: 16) {
                            Button(action: {
                                selectedGender = gender
                            }) {
                                Image(gender.imageName(isSelected: selectedGender == gender))
                                    .resizable()
                                    .scaledToFit()
                                    .frame(width: 140, height: 140)
                            }
                            Text(gender.title)
                                .font(.system(size: 14, weight: .regular))
                                .foregroundColor(selectedGender == gender ? .white : Color(hex: "#B2B2B2"))
                        }
                    }
                    .padding(.all, 0)
                    .frame(width: 140)
                }
                .padding(.top, 32)
                .padding(.horizontal, spacing)
            }
        }
    }
}

struct BirthdaySetupView: View {
    
    @Binding private var selectedDate: Date
        
    init(selectedDate: Binding<Date>) {
        self._selectedDate = selectedDate
    }
    
    
    var body: some View {
        GeometryReader { geometry in
            VStack(alignment: .leading, spacing: 0) {
                HStack(spacing: 10) {
                    Text("您的生日是多少")
                        .font(.title2)
                        .fontWeight(.bold)
                        .foregroundColor(.white)
                        .frame(height: 24)
                    Image("birthday")
                        .resizable()
                        .scaledToFit()
                        .frame(width: 24, height: 24)
                    Spacer()
                }
                .padding(.horizontal, 20)
                Text("APP会根据生日，计算符合你的睡眠习惯")
                    .font(.system(size: 14, weight: .regular))
                    .foregroundColor(Color(hex: "#B2B2B2"))
                    .foregroundColor(.white)
                    .padding(.horizontal, 20)
                    .padding(.top, 16)
                
                HStack {
                    Spacer()
                    DatePicker("", selection: $selectedDate, displayedComponents: .date)
                        .datePickerStyle(.wheel)
                        .labelsHidden()
                        .cornerRadius(10)
                    Spacer()
                }
                .padding(.horizontal, 20)
                .padding(.top, 20)
            }
        }
        .background(Color(hex: "#1E1E1E"))
    }
    
}

struct WeightSetupView: View {
    
    @Binding private var weight: Double
    @Binding private var selectedWeightUnit: WeightUnit
    
        
    init(weight: Binding<Double>, selectedWeightUnit: Binding<WeightUnit>) {
        self._weight = weight
        self._selectedWeightUnit = selectedWeightUnit
    }
    
    private var valueString: String {
        switch selectedWeightUnit {
        case .g:
            return String(format: "%.0f", weight)
        case .kg:
            return String(format: "%.1f", weight)
        }
    }
    
    var body: some View {
        GeometryReader { geometry in
            VStack(alignment: .leading, spacing: 0) {
                HStack(spacing: 10) {
                    Text("您的体重是多少")
                        .font(.title2)
                        .fontWeight(.bold)
                        .foregroundColor(.white)
                        .frame(height: 24)
                    Image("weight")
                        .resizable()
                        .scaledToFit()
                        .frame(width: 24, height: 24)
                    Spacer()
                }
                .padding(.horizontal, 20)
                Text("升高体重不同，热量消耗也有不同，完善体重信息，获取更精准的热量消耗")
                    .font(.system(size: 14, weight: .regular))
                    .foregroundColor(Color(hex: "#B2B2B2"))
                    .foregroundColor(.white)
                    .padding(.horizontal, 20)
                    .padding(.top, 16)
                
                HStack {
                    HStack {
                        Spacer()
                        Button(action: {
                            if (selectedWeightUnit == .kg) {
                                weight = weight * 1000
                            }
                            selectedWeightUnit = .g
                            
                        }) {
                            Text("g")
                                .frame(width: 90, height: 40)
                                .background(WeightUnit.g.bgColor(isSelected: selectedWeightUnit == .g))
                                .foregroundColor(WeightUnit.g.textColor(isSelected: selectedWeightUnit == .g))
                                .cornerRadius(12)
                        }
                        Spacer()
                    }
                    HStack {
                        Spacer()
                        Button(action: {
                            if (selectedWeightUnit == .g) {
                                weight = weight / 1000
                            }
                            selectedWeightUnit = .kg
                        }) {
                            Text("kg")
                                .frame(width: 90, height: 40)
                                .background(WeightUnit.g.bgColor(isSelected: selectedWeightUnit == .kg))
                                .foregroundColor(WeightUnit.g.textColor(isSelected: selectedWeightUnit == .kg))
                                .cornerRadius(12)
                        }
                        Spacer()
                    }
                }
                .padding(.top, 28)
                
                HStack(alignment: .bottom, spacing: 2) {
                    Spacer()
                    Text(valueString)
                        .font(.system(size: 50, weight: .regular))
                        .foregroundColor(Color(hex: "#F5F5F5"))
                        .alignmentGuide(.bottom) { d in d[.bottom] }
                    Text(selectedWeightUnit.rawValue)
                        .font(.system(size: 16, weight: .regular))
                        .foregroundColor(Color(hex: "#B2B2B2"))
                        .alignmentGuide(.bottom) { d in d[.bottom] + 10 }
                    Spacer()
                }
                .padding(.top, 18)
                
                HStack {
                    MeasuringRulerView(type: selectedWeightUnit == .kg ? .weight : .weightG, selectedValue: $weight)
                        .padding(.top, 20)
                        .padding(.horizontal, 20)
                        .edgesIgnoringSafeArea(.bottom)
                }
            }
            .edgesIgnoringSafeArea(.bottom)
        }
        .background(Color(hex: "#1E1E1E"))
    }
}

struct HeightSetupView: View {
    
    @Binding private var height: Double
    @Binding private var selectedHeightUnit: HeightUnit
    
    init(height: Binding<Double>, selectedHeightUnit: Binding<HeightUnit>) {
        self._height = height
        self._selectedHeightUnit = selectedHeightUnit
    }
    
    private var valueString: String {
        switch selectedHeightUnit {
        case .cm:
            return String(format: "%.1f", height)
        case .m:
            return String(format: "%.2f", height)
        }
    }
    
    var body: some View {
        GeometryReader { geometry in
            VStack(alignment: .leading, spacing: 0) {
                HStack(spacing: 10) {
                    Text("您的身高是多少")
                        .font(.title2)
                        .fontWeight(.bold)
                        .foregroundColor(.white)
                        .frame(height: 24)
                    Image("height")
                        .resizable()
                        .scaledToFit()
                        .frame(width: 24, height: 24)
                    Spacer()
                }
                .padding(.horizontal, 20)
                Text("升高体重不同，热量消耗也有不同，完善体重信息，获取更精准的热量消耗")
                    .font(.system(size: 14, weight: .regular))
                    .foregroundColor(Color(hex: "#B2B2B2"))
                    .foregroundColor(.white)
                    .padding(.horizontal, 20)
                    .padding(.top, 16)
                
                HStack {
                    HStack {
                        Spacer()
                        Button(action: {
                            if (selectedHeightUnit == .cm) {
                                height = height / 100
                            }
                            selectedHeightUnit = .m
                            
                        }) {
                            Text("m")
                                .frame(width: 90, height: 40)
                                .background(HeightUnit.m.bgColor(isSelected: selectedHeightUnit == .m))
                                .foregroundColor(HeightUnit.m.textColor(isSelected: selectedHeightUnit == .m))
                                .cornerRadius(12)
                        }
                        Spacer()
                    }
                    HStack {
                        Spacer()
                        Button(action: {
                            if (selectedHeightUnit == .m) {
                                height = height * 100
                            }
                            selectedHeightUnit = .cm
                        }) {
                            Text("cm")
                                .frame(width: 90, height: 40)
                                .background(HeightUnit.cm.bgColor(isSelected: selectedHeightUnit == .cm))
                                .foregroundColor(HeightUnit.cm.textColor(isSelected: selectedHeightUnit == .cm))
                                .cornerRadius(12)
                        }
                        Spacer()
                    }
                }
                .padding(.top, 28)
                
                HStack(alignment: .bottom, spacing: 2) {
                    Spacer()
                    Text(valueString)
                        .font(.system(size: 50, weight: .regular))
                        .foregroundColor(Color(hex: "#F5F5F5"))
                        .alignmentGuide(.bottom) { d in d[.bottom] }
                    Text(selectedHeightUnit.rawValue)
                        .font(.system(size: 16, weight: .regular))
                        .foregroundColor(Color(hex: "#B2B2B2"))
                        .alignmentGuide(.bottom) { d in d[.bottom] + 10 }
                    Spacer()
                }
                .padding(.top, 18)
                
                HStack {
                    MeasuringRulerView(type: selectedHeightUnit == .m ? .heightM : .height, selectedValue: $height)
                        .padding(.top, 20)
                        .padding(.horizontal, 20)
                        
                }
            }
        }
        .background(Color(hex: "#1E1E1E"))
    }
}


struct StepsSetupView: View {
    
    @Binding private var steps: Double
    
    init(steps: Binding<Double>) {
        self._steps = steps
    }
    
    private var valueString: String {
        return String(format: "%.0f", steps)
    }
    
    var body: some View {
        GeometryReader { geometry in
            VStack(alignment: .leading, spacing: 0) {
                HStack(spacing: 10) {
                    Text("请选择目标步数")
                        .font(.title2)
                        .fontWeight(.bold)
                        .foregroundColor(.white)
                        .frame(height: 24)
                    Image("steps")
                        .resizable()
                        .scaledToFit()
                        .frame(width: 24, height: 24)
                    Spacer()
                }
                .padding(.horizontal, 20)
                Text("根据世界卫生组织建议，您每周至少150分钟中等强度有氧活动，相当于每天至少8000步")
                    .font(.system(size: 14, weight: .regular))
                    .foregroundColor(Color(hex: "#B2B2B2"))
                    .foregroundColor(.white)
                    .padding(.horizontal, 20)
                    .padding(.top, 16)
                
                HStack(alignment: .bottom, spacing: 2) {
                    Spacer()
                    Text(valueString)
                        .font(.system(size: 50, weight: .regular))
                        .foregroundColor(Color(hex: "#F5F5F5"))
                        .alignmentGuide(.bottom) { d in d[.bottom] }
                    Text("步")
                        .font(.system(size: 16, weight: .regular))
                        .foregroundColor(Color(hex: "#B2B2B2"))
                        .alignmentGuide(.bottom) { d in d[.bottom] + 10 }
                    Spacer()
                }
                .padding(.top, 54)
                
                HStack {
                    MeasuringRulerView(type: .steps, selectedValue: $steps)
                        .padding(.top, 20)
                        .padding(.horizontal, 20)
                        
                }
            }
        }
        .background(Color(hex: "#1E1E1E"))
    }
}


//#Preview {
////    StepsSetupView()
////    OnboardingView()
//}
